<?php

namespace App\Services\ApplySeckillProductBatchPay;

use Closure;
use App\Models\User;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Api\V1\Requests\FormRequest;

class ApplySeckillProductBatchPayRequest extends FormRequest
{
	protected array $unpaidCacheIds = [];

	public function rules(): array
	{
		return [
			'cache_ids' => ['required','array', $this->seckillCache()]
		];
	}

	public function seckillCache(): Closure
	{
		return function ($key, $value, $fail) {
			/**
			 * @var User $user
			 */
			$user = $this->user();

			$needMoney  = big_decimal(0);

			foreach ($value as $cacheId) {

				if (! $user->isOrderInUnpaidCache($cacheId)) {
					return $fail('目标订单不存在或已过期');
				} elseif (! Redis::exists($cacheId)) {
					return $fail("目标订单不存在:{$cacheId}");
				} elseif (Redis::hGet($cacheId, 'is_paying')) {
					return $fail("目标订单已申请付款:{$cacheId}");
				} elseif (Redis::hGet($cacheId, 'is_paid')) {
					return $fail("目标订单已付款:{$cacheId}");
				} elseif (Redis::hGet($cacheId, 'closed_at')) {
					return $fail("目标订单已关闭:{$cacheId}");
				}
				$needMoney = $needMoney->plus(Redis::hGet($cacheId, 'price_vip'));

			}
			

			if (big_decimal($needMoney)->isGreaterThan($user->balance)) {
				return $fail('账户余额不足');
			}


			return true;
		};
	}

	
}
